<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form 
        :model="localUserInfo" 
        label-width="120px" 
        :rules="formRules" 
        ref="form"  
        status-icon 
      >
        <el-form-item label="用户名" :label-width="labelWidth" prop="username">
          <el-input v-model="localUserInfo.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="邮箱" :label-width="labelWidth" prop="email">
          <el-input v-model="localUserInfo.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="电话" :label-width="labelWidth" prop="phonenumber">
          <el-input v-model="localUserInfo.phonenumber" placeholder="请输入电话" />
        </el-form-item>

        <el-form-item label="备注" :label-width="labelWidth" prop="remark">
          <el-input type="textarea" v-model="localUserInfo.remark" placeholder="请输入备注" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { defineProps, defineEmits, ref } from 'vue';
// 接收父组件传递的 props 数据
const props = defineProps({
  userInfo: {
    type: Object,
    required: true
  }
});

// 向父组件发送事件
const emit = defineEmits(['update:userInfo']);

// 控制标签宽度
const labelWidth = '120px';

// 使用 ref 来创建本地副本
const localUserInfo = ref({
  username: props.userInfo.username,
  email: props.userInfo.email,
  phonenumber: props.userInfo.phonenumber,
  remark: props.userInfo.remark
});

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为 3 至 20 个字符', trigger: 'blur' }
  ],
  email: [
    // { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phonenumber: [
    // { required: true, message: '电话号码不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的电话号码', trigger: ['blur', 'change'] }
  ],
  remark: [
    { required: false, message: '备注不能为空', trigger: 'blur' }
  ]
};

// 创建一个 ref 用来引用 el-form
const form = ref();

// 提交表单
const submitForm = () => {
  // 调用表单验证
  form.value.validate((valid) => {
    if (valid) {
      console.log('提交的数据:', localUserInfo.value);
      // 你可以在这里处理保存数据的操作，例如发送 API 请求
      // 创建请求数据对象
      const data = {
        username: localUserInfo.value.username,
        email: localUserInfo.value.email,
        phonenumber: localUserInfo.value.phonenumber,
        remark: localUserInfo.value.remark
      };
      // 直接使用拦截器中自动添加的 token，无需手动设置
      axios.patch('user/update_user_info/', data)
      .then((response) => {
        if (response.data.code === 200){
          // 请求成功时的回调
          console.log('修改成功:', response.data);
          // 更新数据
          localStorage.setItem('userInfo',JSON.stringify(response.data.data))
          // 
          ElMessage.success({
          message: response.data.msg || 'Token expired or invalid. Please login again.',
          duration: 1000 // 消息显示的持续时间，单位为毫秒
        });
          // 发送成功后，刷新页面
          window.location.reload()
        }else{
          console.log(response.data)
        }

      })
      .catch((error) => {
        // 请求失败时的回调
        console.error('修改失败:', error.response ? error.response.data : error);
        alert('修改信息失败！');
      });
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  localUserInfo.value = { ...props.userInfo };
};
</script>

<style scoped>
.app-container {
  background-color: #f9f9f9;
  width: 100%;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.box-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  width: 100%;
}

.el-button {
  margin-right: 10px;
}

.el-form-item .el-input {
  min-width: 200px;
}
</style>
